var FZJ = {};
var fzjMap = {};
var orderMap = {};
var orderStrIds = [];

//刷新页面信息
$(function () {
    var bodyWidth = document.documentElement.clientWidth;
    var bodyHeight = document.documentElement.clientHeight;
    $("#fac_tab").css('width', bodyWidth - 460 - Math.floor(bodyWidth / 22));
    $("#orderTable").css('height', bodyHeight - 90);
    $("#fzjUl").css('height', bodyHeight - 90);
    orderStrIds = top.OB.Emes_ActionButton.AssignOrders.ids;
    var data = {
        ids: orderStrIds,
        type: "NONE"
    };
    top.OB.RemoteCallManager.call("com.mes.handler.plan.JobOrderAssignHandler", data, {}, function (response, data) {
        if (data.result) {
            FZJ = data;
            refreshFZJ(data.facList);
            refreshOrders(data.orderList);

            setTimeout(function () {
                addSorts();
            }, 500);
        }
    });

    //判断是否一键派工之后操作
    if (top.OB.Emes_ActionButton.AssignOrders.generate && orderStrIds != '') {
        generatematerialList(orderStrIds);
    }
});
function generatematerialList(ids) {
    top.isc.confirm("是否将派工之后订单生成备料单？", function(ok) {
        if (ok) {
            top.OB.RemoteCallManager.call(
                "com.mes.handler.plan.GenerateMaterialHandler", {
                    ids : ids
                }, {}, function(request, data) {
                    if (data.flag) {
                        top.OB.Emes_ActionButton.AssignOrders.generate = false;
                        if (top.OB.Emes_ActionButton.orderAssignOpenWindow) {
                            top.OB.Emes_ActionButton.orderAssignOpenWindow.refresh();
                        }
                    }
                    top.isc.showMessage(data.message);
                });
        }
    });
}
//飞织机数据
function refreshFZJ(data) {
    var fzjStr = [];
    var fzjList = data;
    for (i = 0; i < fzjList.length; i++) {
        var fzj = fzjList[i];
        fzjStr.push('<div class="thumbnails" style="width: 190px;height: 150px;float: left;margin: 5px; border-radius: 3px;overflow: hidden;">');
        fzjStr.push('<div class="thumbnail" ');
        if (fzj.run_status == 'RUN') {
            fzjStr.push('style="background-color: #ACD2AC"');
        } else if (fzj.run_status == 'ERROR') {
            fzjStr.push('style="background-color: #FFC66D"');
        } else {
            fzjStr.push('style="background-color: #FDF8D4"');
        }
        fzjStr.push('><div class="caption" id="' + fzj.id + '" style="border-radius: 3px;cursor: pointer;" onclick="openTaskList(\'' + fzj.id +'\')">');
        fzjStr.push('<h3 style="margin-top: 0px;">' + fzj.code + '&nbsp;');
        fzjStr.push('(<span style="color: #99332C;font-weight: bold;" id="' + fzj.id + '_count">' + fzj.count + '</span>)</h3>');
        fzjStr.push('<div style="height: 60px;overflow: auto;">');

        fzjMap[fzj.id] = {};

        if (fzj.colors) {
            var colors = [];
            for (var j = 0; j < fzj.colors.length; j++) {
                colors.push('<div style="margin-top: 0px;">' + fzj.colors[j].pcode + " 【" + fzj.colors[j].name + '】</div>');
                fzjMap[fzj.id][fzj.colors[j].pcode + "-" + fzj.colors[j].name] = true;
            }
            fzjStr.push(colors.join(""));
        }
        fzjStr.push('</div>');
        fzjStr.push('</div>');
        fzjStr.push('</div>');
        fzjStr.push('</div>');
    }

    $("#fzjUl").append(fzjStr.join(""));
}

//订单数据
function refreshOrders(data) {
    var ordStr = [];
    var orderList = data;
    for (i = 0; i < orderList.length; i++) {
        var order = orderList[i];
        ordStr.push('<div class="list-group-item tinted" id="' + order.id + '" qty="' + order.qtys + '">' +
            '【' + order.code + '】/ ' + order.pCode + ' / ' + order.color + ' / ' + order.size +
            ' / <span style="color: #99332C;">' + order.qtys + '</span></div>');
        orderMap[order.id] = order;
    }
    $("#orderTable").append(ordStr.join(""));
}

var moveItems = [];
var facId;
//初始化排序功能
function addSorts() {
    Sortable.create($("#orderTable")[0], {
        group: 'shared',
        multiDrag: true,
        selectedClass: "selected",
        animation: 150,
        onEnd: function (evt) { //拖拽完毕之后发生该事件
            if (evt.to.id != 'orderTable') {
                facId = evt.to.id;
                moveItems = evt.items;
                if (!moveItems || moveItems.length == 0) {
                    moveItems = [evt.item];
                }
                $(evt.to).find(".list-group-item").hide();

                if (!checkOrderColor()) {
                    return;
                }
                if (moveItems.length == 1) {
                    var order = orderMap[moveItems[0].id];
                    //如果单个派工单的数量超过2个时则弹出指定派工数量弹出框
                    if (order.qtys > 1) {
                        $("#assginQty").val(order.qtys);
                        $('#qtyModal').modal();
                        return;
                    }
                }

                saveChange();
            }
        }
    });

    for(var i = 0 ; i < FZJ.facList.length ; i ++) {
        var fzj = $('#' + FZJ.facList[i].id);
        fzj.mousemove(function(event) {
            $(this).css('background-color', '#cccccc');
        });
        fzj.mouseout(function(event) {
            $(this).css('background-color', '');
        });

        Sortable.create(fzj[0], {
            group: 'shared',
            multiDrag: false,
            animation: 150,
            draggable: '.list-group-item',
            onEnd: function(evt){ //拖拽完毕之后发生该事件
            },
            onUpdate: function (evt){ //拖拽更新节点位置发生该事件
            },
            onMove: function (/**Event*/evt, /**Event*/originalEvent) {
                this.disabled = true;
            },
            onAdd: function (/**Event*/evt) {
            }
        });
    }
}
function checkOrderColor() {
    //验证工单与飞织机形体、颜色是否能匹配
    for (var i = 0;i < moveItems.length;i ++) {
        var order = orderMap[moveItems[i].id];
        if (!order || !fzjMap[facId][order.pCode + '-' + order.color]) {
            $('#msgDiv').html("当前飞织机没有匹配选择订单对应的形体颜色！");
            window.setTimeout(function() {
                $('#msgDiv').html('');
            }, 3000);
            //将拖拽的工单返回
            rollback(facId, moveItems);
            return false;
        }
    }
    return true;
}
function saveChange() {
    var orderIds = [];
    var nums = [];
    for (var i = 0; i < moveItems.length; i++) {
        var order = orderMap[moveItems[i].id];
        if (order && fzjMap[facId][order.pCode + '-' + order.color]) {
            orderIds.push(moveItems[i].id);
            nums.push(moveItems[i].getAttribute("qty"));
        }
    }
    submitAssign(orderIds, nums);
}
function submitAssign(orderIds, nums) {
    var data = {
        facId: facId,
        nums: nums.join(","),
        orderIds: orderIds.join(","),
        type: "submit"
    };
    top.OB.RemoteCallManager.call("com.mes.handler.plan.JobOrderAssignHandler", data, {}, function (response, data, request) {
        $('#msgDiv').html(data.msg);
        window.setTimeout(function() {
            $('#msgDiv').html('');
        }, 2000);
        if (data.result) {
            var count = $('#' + facId + '_count').html() * 1;
            for (var i = 0;i < moveItems.length;i ++) {
                count += nums[i] * 1;
                $(moveItems[i]).remove();
            }
            $('#' + facId + '_count').html(count);

            if (moveItems.length == 1) {
                $('#qtyModal').modal("hide");
                var order = orderMap[moveItems[0].id];

                if (order.qtys > nums[0]) {
                    order.qtys = order.qtys - nums[0];
                    moveItems[0].setAttribute("qty", order.qtys);
                    moveItems[0].innerHTML = '【' + order.code + '】/ ' + order.pCode + ' / ' + order.color + ' / ' + order.size +
                    ' / <span style="color: #99332C;">' + order.qtys + '</span>';
                    $("#orderTable").append(moveItems[0]);
                    $(moveItems[0]).show();
                }
            }
            if (top.OB.Emes_ActionButton.orderAssignOpenWindow) {
                top.OB.Emes_ActionButton.orderAssignOpenWindow.refresh();
            }
            moveItems = [];
        } else {
            rollback(facId, moveItems);
        }
    });
}
function subOrderAssign() {
    var qty = $("#assginQty").val() * 1;
    if (!/^[1-9]\d*$/.test(qty)) {
        $("#qtyErrorMsg").html("数量格式不正确！");
        window.setTimeout(function() {
            $('#qtyErrorMsg').html('');
        }, 2000);
        return;
    }
    var order = orderMap[moveItems[0].id];
    if (qty > order.qtys) {
        $("#qtyErrorMsg").html("派工数量不能大于订单数量！");
        window.setTimeout(function() {
            $('#qtyErrorMsg').html('');
        }, 2000);
        return;
    }
    var orderIds = [moveItems[0].id];
    var nums = [qty];
    submitAssign(orderIds, nums);
}
function cancelOrderAssign() {
    $('#qtyModal').modal("hide");
    rollback(facId, moveItems);
}
function rollback(facId, moveItems) {
    if (moveItems && moveItems.length > 0) {
        for (var i = 0;i < moveItems.length;i ++) {
            $(moveItems[i]).show();
            $("#orderTable").append(moveItems[i]);
        }
    }
}
function openTaskList(facId) {
    top.OB.RemoteCallManager.call("com.mes.handler.plan.JobOrderAssignHandler", {facId: facId, type: "orders"}, {}, function (response, data, request) {
        if (data.result) {
            var list = data.list;
            $('#fzj_orders').find('.list-group-item').remove();

            var html = [];
            jobOrders = [];
            for (var i = 0;i < list.length;i ++) {
                var order = list[i];
                html.push('<div class="list-group-item tinted" id="' + order.id + '">' +
                    '【' + order.code + '】/ 【' + order.moCode + '】 / ' + order.color + ' / ' + order.size);
                //已下发到飞织机
                if (order.xfStatus != 'Y') {
                    html.push('<button type="button" class="close" onclick="delJobOrder(\'' + order.id + '\')">&times;</button>');
                }
                html.push('</div>');
            }
            $('#fzj_orders').append(html.join(''));
            $('#myModal').modal();
        } else {
            $('#msgDiv').html(data.msg);
            window.setTimeout(function() {
                $('#msgDiv').html('');
            }, 2000);
        }
    });
}
var jobOrders = [];
function delJobOrder(jobId) {
    jobOrders.push(jobId);
    $('#' + jobId).remove();
}
function subDelJobOrder() {
    if (jobOrders.length == 0) {
        return;
    }
    top.OB.RemoteCallManager.call("com.mes.handler.plan.JobOrderAssignHandler", {jobOrders: jobOrders.join(","), type: 'del'}, {}, function (response, data, request) {
        top.isc.showMessage(data.msg);
        if (data.result) {
            $('#myModal').modal('hide');
            top.OB.Emes_ActionButton.AssignOrders.generate = false;
            window.location.reload();
        }
    });
}
function oneKeyAssign() {
    if (orderStrIds.length == 0) {
        $('#msgDiv').html("无可派工工单！");
        window.setTimeout(function() {
            $('#msgDiv').html('');
        }, 2000);
        return;
    }
    top.isc.confirm("确认一键派工？", function(ok) {
        if (ok) {
            top.OB.RemoteCallManager.call("com.mes.handler.plan.JobOrderAssignHandler", {
                ids: orderStrIds,
                type: 'oneKey'
            }, {}, function (response, data) {
                $('#msgDiv').html(data.msg);
                if (data.result) {
                    top.OB.Emes_ActionButton.AssignOrders.ids = data.ids;
                    top.OB.Emes_ActionButton.AssignOrders.generate = true;
                    window.setTimeout(function () {
                        if (top.OB.Emes_ActionButton.orderAssignOpenWindow) {
                            top.OB.Emes_ActionButton.orderAssignOpenWindow.refresh();
                        }
                        window.location.reload();
                    }, 1000);
                }
            });
        }
    });
}